import React, { useState } from "react";

import { Button, Table, Modal, Form, Input, InputNumber, Radio, Popconfirm } from "antd";

import { ColumnProps } from "antd/es/table";

import { useQuery, useMutation } from "@apollo/client";
import { GET_USERS, ADD_USER, EDIT_USER, RM_USER } from "./request";

import "./index.css";

interface User {
  name: string;
  age: number;
  gender: number;
  id: string;
  createdAt: any;
}

function User() {
  const [visible, setVisible] = useState<boolean>(false);
  const [isEdit, setIsEdit] = useState<boolean>(false);
  const [editTarget, setEditTarget] = useState<User>();
  const [userForm] = Form.useForm();
  const { loading, data = {}, refetch: refetchUsers } = useQuery(GET_USERS);
  const [addUser, { loading: addLoading }] = useMutation(ADD_USER);
  const [editUser, { loading: editLoading }] = useMutation(EDIT_USER);
  const [deleteUser, { loading: deleteLoading }] = useMutation(RM_USER);

  const openHandle = () => {
    setVisible(true);
  };

  const oncancel = () => {
    userForm.resetFields();
    setIsEdit(false);
    setVisible(false);
  };

  const openEdit = (user: User) => {
    userForm.setFieldsValue({
      name: user.name,
      age: user.age,
      gender: user.gender,
    });
    setEditTarget(user);
    setIsEdit(true);
    setVisible(true);
  };

  const startDelete = async (user: User) => {
    deleteUser({
      variables: {
        id: user.id
      }
    });
    userForm.resetFields();
    refetchUsers();
  };

  const onsubmit = async () => {
    const values = await userForm.validateFields();
    if (isEdit) {
      await editUser({
        variables: {
          id: editTarget.id,
          user: values,
        }
      });
    } else {
      await addUser({
        variables: {
          user: values,
        },
      });
    }
    userForm.resetFields();
    await refetchUsers();
    setIsEdit(false);
    setVisible(false);
  };

  const columns: ColumnProps<User>[] = [
    {
      title: "名称",
      dataIndex: "name",
    },
    {
      title: "创建时间",
      dataIndex: "createdAt",
    },
    {
      title: "性别",
      dataIndex: "gender",
    },
    {
      title: "年龄",
      dataIndex: "age",
    },
    {
      title: "操作",
      key: "actions",
      render(_, record) {
        return (
          <div>
            <Button type="link" size="small" onClick={() => openEdit(record)}>
              编辑
            </Button>
            <Popconfirm
              title="Are you sure to delete this user?"
              onConfirm={() => startDelete(record)}
            >
              <Button type="link" size="small">删除</Button>
            </Popconfirm>
          </div>
        );
      },
    },
  ];

  return (
    <div className="container">
      <div className="top">
        <Button onClick={openHandle}>新增用户</Button>
      </div>

      <div className="body">
        <Table
          columns={columns}
          bordered
          loading={loading}
          dataSource={data.users}
          rowKey="id"
        ></Table>
      </div>

      <Modal
        visible={visible}
        title={isEdit ? "编辑用户信息" : "新建用户"}
        onCancel={oncancel}
        onOk={onsubmit}
        confirmLoading={addLoading}
        forceRender
      >
        <Form
          form={userForm}
          labelCol={{ span: 6 }}
        >
          <Form.Item
            name="name"
            label="名称"
            rules={[{ required: true, message: "请输入" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="age"
            label="年龄"
            rules={[{ required: true, message: "请输入" }]}
          >
            <InputNumber min={0} />
          </Form.Item>
          <Form.Item
            name="gender"
            label="性别"
            rules={[{ required: true, message: "请输入" }]}
          >
            <Radio.Group>
              <Radio value={1}>男</Radio>
              <Radio value={0}>女</Radio>
            </Radio.Group>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}

export default User;
